<template >
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加用户 -->
      <el-row :gutter="18">
        <el-col :span="6">
          <!-- 输入input -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户数据的表格显示 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 这内部加了属性绑定 :data = userlist.obj-->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserid(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 4, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
        <!-- 内容区域 -->
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog title="编辑用户" :visible.sync="editVisible" width="50%" @close="editClose">
        <!-- 内容区域 -->
        <el-form
          :model="editForm"
          status-icon
          :rules="editFormrules"
          ref="editFormRef"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input type="text" v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="text" v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input type="text" v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserDemo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除用户提示框 -->
      <!-- 分配角色提示框 -->
      <el-dialog title="分配角色" :visible.sync="setRoleVisible" width="30%" @close="setRoleclose">
        <div>
          <p>用户名称：{{userInfo.username}}</p>
          <p>角色名称：{{userInfo.role_name}}</p>
          <el-select v-model="selectRoleId" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <!-- <div>角色名称：{{userInfo.role_name}}</div> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  name: "users",
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 手机号码
    const checkMobile = (rule, value, cb) => {
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {},
      queryInfo: {
        query: "",
        // 当前的页码
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      userInfo: {},
      roleList: [],
      selectRoleId: "",
      dialogVisible: false,
      setRoleVisible: false,
      editVisible: false,
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      editFormrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      console.log(res);

      console.log(res.meta.status);

      if (res.meta.status !== 200) return this.$message.error("获取用户失败");
      this.userList = res.data.users;

      this.total = res.data.total;
      console.log(this.total);
      console.log(this.userList);
    },
    handleSizeChange(val) {
      console.log(val);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    async userStateChange(userinfo) {
      // console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(res);

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        // 如果校验不通过
        if (!valid) return;
        // 发起网络请求
        const { data: res } = await this.$http.post("users", this.addUserForm);
        console.log(res);
        if (res.meta.status != 201) return this.$message.error("添加用户失败");
        this.getUserList();
        this.dialogVisible = false;
        return this.$message.success("添加用户成功");
      });
    },
    editClose() {
      this.$refs.editFormRef.resetFields();
    },
    async editUser(val) {
      console.log(val);
      const { data: res } = await this.$http.get(`users/${val}`);
      this.editVisible = true;
      console.log(res.data);

      this.editForm = res.data;
    },
    editUserDemo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        // 发起请求
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        );
        if (res.meta.status != 200) return this.$message.error("更新失败");
        console.log(res.data);
        this.getUserList();
        this.editVisible = false;
        this.$message.success("更新成功");
      });
    },
    async setRole(val) {
      this.userInfo = val;
      this.setRoleVisible = true;
      const { data: res } = await this.$http.get("roles");
      this.roleList = res.data;
    },
    async removeUserid(val) {
      const con = await this.$confirm(
        "此操作将永久删除该用户，是否继续",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      // console.log(con);
      if (con !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete(`users/${val}`);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.getUserList();
      this.$message.success("删除成功");
    },
    async setRoleInfo() {
      if (!this.selectRoleId)
        return this.$message.error("怎么回事啊，选角色啊");
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}`, {
        rid: this.selectRoleId
      });
      if (res.meta.status !== 200) return this.$message.error("失败");
      this.$message.success("成功");
      this.getUserList();
      this.setRoleVisible = false;
    },
    setRoleclose() {
      this.selectRoleId = ''
    }
  },
  created() {
    this.getUserList();
  }
};
</script>
<style lang="scss" scoped>
</style>